#!/usr/bin/ruby

require 'optparse'

RELPATH = File.expand_path(File.dirname(__FILE__))

TMPPATH = RELPATH + "/tmp/"
SRCPATH = RELPATH + "/cs_src/"
FINALPATH = RELPATH + "/cs_final/"
PROTOPATH = RELPATH + "/proto/"

$options = {:verbose => false}

OptionParser.new do |opts|
  opts.on('-V', '--verbose', '') do
    $options[:verbose] = true
  end
end.parse(ARGV)

module Compile
  def exec(command)
    puts command if $options[:verbose]
    system command
  end

  def clean dirName
    exec "mkdir -p #{dirName}"
  end

  def protoc
    Dir["#{PROTOPATH}**/*.proto"].each do |file|
      exec "wine ./lib/protoc.exe --proto_path=#{PROTOPATH} #{file} --include_imports --descriptor_set_out=#{TMPPATH}#{File.basename(file)}.pb"
    end
  end

  def protogen
    Dir["#{TMPPATH}**/*.pb"].each do |file|
      exec "wine ./lib/protogen.exe #{file} -output_directory=#{SRCPATH}"
    end
  end

  def parse
    Dir["#{SRCPATH}**/*.cs"].each do |file|
      exec "python ./lib/parse_proto.py #{file} #{FINALPATH}#{File.basename(file)}"
    end
  end

  def after
    exec "mkdir -p build"
    exec "./protobuf_magician"
    exec "./error_code"
    exec "mv ./build/netmsg_id.cs #{FINALPATH}"
    exec "mv ./build/netmsg_json.cs #{FINALPATH}"
    exec "rm -rf #{FINALPATH}CSharpOptions.cs"
    exec "rm -rf #{FINALPATH}DescriptorProtoFile.cs"
    exec "git show -s --format=%H > #{FINALPATH}/protocol_version"
  end

  extend self
end

Compile.clean TMPPATH
Compile.protoc
Compile.clean SRCPATH
Compile.protogen
Compile.clean FINALPATH
Compile.parse
Compile.after
